﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq;
using System.Data.Entity;
using AppBox.BLL;
using FineUI;
using EntityFramework.Extensions;
using ZHDJ.Data.Models.Box;
using ZHDJ.Data.Models.Org;
using ZHDJ.WebPage;
using PageBase = AppBox.BLL.PageBase;

namespace AppBox.admin
{
    public partial class role_user : BLL.PageBase
    {
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "CoreRoleUserView";
            }
        }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            // 权限检查
            CheckPowerWithButton("CoreRoleUserNew", btnNew);
            CheckPowerWithButton("CoreRoleUserDelete", btnDeleteSelected);


            ResolveDeleteButtonForGrid(btnDeleteSelected, Grid2, "确定要从当前角色移除选中的{0}项记录吗？");


            BindGrid1();

            // 默认选中第一个角色
            Grid1.SelectedRowIndex = 0;

            // 每页记录数
            Grid2.PageSize = ConfigHelper.PageSize;
            ddlGridPageSize.SelectedValue = ConfigHelper.PageSize.ToString();

            BindGrid2();
        }

        private void BindGrid1()
        {
            IQueryable<Role> q = DB.Roles;

            // 排列
            q = Sort<Role>(q, Grid1);

            Grid1.DataSource = q;
            Grid1.DataBind();
        }

        private void BindGrid2()
        {
            string roleID = GetSelectedDataKeyID(Grid1);

            if (roleID == "-1")
            {
                Grid2.RecordCount = 0;

                Grid2.DataSource = null;
                Grid2.DataBind();
            }
            else
            {
                IQueryable<PartyOrgMember> q = DB.PartyOrgMembers;

                // 在用户名称中搜索
                string searchText = ttbSearchUser.Text.Trim();
                if (!String.IsNullOrEmpty(searchText))
                {
                    q = q.Where(u => u.UserName.Contains(searchText)|| u.LoginID.Contains(searchText));
                }

                q = q.Where(u => u.LoginID != "admin");

                // 过滤选中角色下的所有用户
                q = q.Where(u => u.Roles.Any(r => r.ID == roleID));

                // 在查询添加之后，排序和分页之前获取总记录数
                Grid2.RecordCount = q.Count();

                // 排列和分页
                q = SortAndPage<PartyOrgMember>(q, Grid2);

                Grid2.DataSource = q;
                Grid2.DataBind();
            }

        }

        #endregion

        #region Events

        protected void ddlGridPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid2.PageSize = Convert.ToInt32(ddlGridPageSize.SelectedValue);

            BindGrid2();
        }


        #endregion

        #region Grid1 Events

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
			Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid1();

            // 默认选中第一个角色
            Grid1.SelectedRowIndex = 0;

            BindGrid2();
        }

        protected void Grid1_RowClick(object sender, FineUI.GridRowClickEventArgs e)
        {
            BindGrid2();
        }

        #endregion

        #region Grid2 Events

        protected void Grid2_PreDataBound(object sender, EventArgs e)
        {
            // 数据绑定之前，进行权限检查
            CheckPowerWithLinkButtonField("CoreRoleUserDelete", Grid2, "deleteField");
        }

        protected void Grid2_Sort(object sender, GridSortEventArgs e)
        {
			Grid2.SortDirection = e.SortDirection;
            Grid2.SortField = e.SortField;
            BindGrid2();
        }

        protected void Grid2_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid2.PageIndex = e.NewPageIndex;
            BindGrid2();
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!CheckPower("CoreRoleUserDelete"))
            {
                CheckPowerFailWithAlert();
                return;
            }

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            string roleID = GetSelectedDataKeyID(Grid1);
            List<string> userIDs = GetSelectedDataKeyIDs(Grid2);

            Role role = DB.Roles.Include(r => r.Users)
                .Where(r => r.ID == roleID)
                .FirstOrDefault();

            //role.Users.Where(u => userIDs.Contains(u.ID)).ToList().ForEach(u => role.Users.Remove(u));
            foreach (string loginID in userIDs)
            {
                PartyOrgMember user = role.Users.Where(u => u.LoginID == loginID).FirstOrDefault();
                if (user != null)
                {
                    role.Users.Remove(user);
                }
            }

            DB.SaveChanges();

            // 清空当前选中的项
            Grid2.SelectedRowIndexArray = null;

            // 重新绑定表格
            BindGrid2();
        }

        protected void Grid2_RowCommand(object sender, GridCommandEventArgs e)
        {
            object[] values = Grid2.DataKeys[e.RowIndex];
            string loginID = Convert.ToString(values[0]);

            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                if (!CheckPower("CoreRoleUserDelete"))
                {
                    CheckPowerFailWithAlert();
                    return;
                }

                string roleID = GetSelectedDataKeyID(Grid1);

                Role role = DB.Roles.Include(r => r.Users)
                    .Where(r => r.ID == roleID)
                    .FirstOrDefault();

                PartyOrgMember tobeRemovedUser = role.Users.Where(u => u.LoginID == loginID).FirstOrDefault();
                if (tobeRemovedUser != null)
                {
                    role.Users.Remove(tobeRemovedUser);
                    DB.SaveChanges();
                }

                BindGrid2();
            }
        }

        protected void Window1_Close(object sender, EventArgs e)
        {
            BindGrid2();
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            string roleID = GetSelectedDataKeyID(Grid1);
            string addUrl = String.Format("~/app/box/admin/role_user_addnew.aspx?id={0}", roleID);

            PageContext.RegisterStartupScript(Window1.GetShowReference(addUrl, "添加用户到当前角色"));
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid2();
        }
        #endregion

    }
}
